using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Pegasus.Collections.Generic
{
	/// <summary>
	/// This class will hold the given value for the Time To Live (TTL) seconds.  At which time the object
	/// is removed from the collection.
	/// </summary>
	/// <typeparam name="TKey"></typeparam>
	/// <typeparam name="TValue"></typeparam>
	public class DictionaryCache<TKey, TValue> : IDictionary<TKey, TValue>
	{
		// Local Instance Values
		private Dictionary<TKey, DataNode<TValue>> m_dictionary = new Dictionary<TKey, DataNode<TValue>>();
		private List<TKey> m_cachedKeyList = null;
		private List<TValue> m_cachedValueList = null;

		/// <summary>
		/// Initializes a new instance of the <see cref="T:DictionaryCache&lt;TKey, TValue&gt;"/> class.
		/// </summary>
		public DictionaryCache() :
			this( 300 )
		{
			// TODO: Not finished yet.  Need to think about how to clean out the expireed elements.
			throw new NotImplementedException();
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="T:DictionaryCache&lt;TKey, TValue&gt;"/> class.
		/// </summary>
		/// <param name="ttl">The TTL number of seconds for the object to live in the cache.</param>
		public DictionaryCache( int ttl )
		{
			DataNode<TValue>.TTL = ttl;
			throw new NotImplementedException();
		}

		/// <summary>
		/// Gets or sets the TTL in seconds.
		/// </summary>
		/// <value>The TTL.</value>
		public int TTL
		{
			get
			{
				return DataNode<TValue>.TTL;
			}

			set
			{
				DataNode<TValue>.TTL = value;
			}
		}

		/// <summary>
		/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"></see> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.
		/// </summary>
		/// <value></value>
		/// <returns>An <see cref="T:System.Collections.Generic.ICollection`1"></see> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"></see>.</returns>
		public ICollection<TKey> Keys
		{
			get
			{
				lock( m_dictionary )
				{
					if( m_cachedKeyList == null )
					{
						m_cachedKeyList = new List<TKey>();
						foreach( TKey key in m_dictionary.Keys )
						{
							m_cachedKeyList.Add( key );
						}
					}

					return m_cachedKeyList;
				}
			}
		}

		/// <summary>
		/// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.
		/// </summary>
		/// <param name="key">The object to use as the key of the element to add.</param>
		/// <param name="value">The object to use as the value of the element to add.</param>
		/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"></see> is read-only.</exception>
		/// <exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.</exception>
		/// <exception cref="T:System.ArgumentNullException">key is null.</exception>
		public void Add( TKey key, TValue value )
		{
			lock( m_dictionary )
			{
				m_dictionary.Add( key, new DataNode<TValue>( value ) );
				ClearCachedLists();
			}
		}

		/// <summary>
		/// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"></see> contains an element with the specified key.
		/// </summary>
		/// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.</param>
		/// <returns>
		/// true if the <see cref="T:System.Collections.Generic.IDictionary`2"></see> contains an element with the key; otherwise, false.
		/// </returns>
		/// <exception cref="T:System.ArgumentNullException">key is null.</exception>
		public bool ContainsKey( TKey key )
		{
			lock( m_dictionary )
			{
				return m_dictionary.ContainsKey( key );
			}
		}

		/// <summary>
		/// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.
		/// </summary>
		/// <param name="key">The key of the element to remove.</param>
		/// <returns>
		/// true if the element is successfully removed; otherwise, false.  This method also returns false if key was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"></see>.
		/// </returns>
		/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"></see> is read-only.</exception>
		/// <exception cref="T:System.ArgumentNullException">key is null.</exception>
		public bool Remove( TKey key )
		{
			lock( m_dictionary )
			{
				ClearCachedLists();
				return m_dictionary.Remove( key );
			}
		}

		/// <summary>
		/// Tries the get value.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <param name="value">The value.</param>
		/// <returns></returns>
		public bool TryGetValue( TKey key, out TValue value )
		{
			lock( m_dictionary )
			{
				DataNode<TValue> nodeValue;
				value = default( TValue );

				bool ret = m_dictionary.TryGetValue( key, out nodeValue );
				if( ret )
				{
					value = nodeValue.Value;
				}

				return ret;
			}
		}

		/// <summary>
		/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"></see> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.
		/// </summary>
		/// <value></value>
		/// <returns>An <see cref="T:System.Collections.Generic.ICollection`1"></see> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"></see>.</returns>
		public ICollection<TValue> Values
		{
			get
			{
				lock( m_dictionary )
				{
					if( m_cachedValueList == null )
					{
						m_cachedValueList = new List<TValue>();
						foreach( DataNode<TValue> nodeValue in m_dictionary.Values )
						{
							m_cachedValueList.Add( nodeValue.Value );
						}
					}

					return m_cachedValueList;
				}
			}
		}

		/// <summary>
		/// Gets or sets the <see cref="T:TValue"/> with the specified key.
		/// </summary>
		/// <value></value>
		public TValue this[ TKey key ]
		{
			get
			{
				lock( m_dictionary )
				{
					DataNode<TValue> dataNode = m_dictionary[ key ];
					if( dataNode != null )
					{
						return dataNode.Value;
					}

					return default( TValue );
				}
			}

			set
			{
				lock( m_dictionary )
				{
					m_dictionary[ key ] = new DataNode<TValue>( value );
					ClearCachedLists();
				}
			}
		}

		/// <summary>
		/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"></see>.
		/// </summary>
		/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param>
		/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only.</exception>
		public void Add( KeyValuePair<TKey, TValue> item )
		{
			lock( m_dictionary )
			{
				m_dictionary.Add( item.Key, new DataNode<TValue>( item.Value ) );
				ClearCachedLists();
			}
		}

		/// <summary>
		/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"></see>.
		/// </summary>
		/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only. </exception>
		public void Clear()
		{
			lock( m_dictionary )
			{
				m_dictionary.Clear();
				ClearCachedLists();
			}
		}

		/// <summary>
		/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"></see> contains a specific value.
		/// </summary>
		/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param>
		/// <returns>
		/// true if item is found in the <see cref="T:System.Collections.Generic.ICollection`1"></see>; otherwise, false.
		/// </returns>
		public bool Contains( KeyValuePair<TKey, TValue> item )
		{
			lock( m_dictionary )
			{
				return m_dictionary.ContainsKey( item.Key );
			}
		}

		/// <summary>
		/// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"></see> to an <see cref="T:System.Array"></see>, starting at a particular <see cref="T:System.Array"></see> index.
		/// </summary>
		/// <param name="array">The one-dimensional <see cref="T:System.Array"></see> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"></see>. The <see cref="T:System.Array"></see> must have zero-based indexing.</param>
		/// <param name="arrayIndex">The zero-based index in array at which copying begins.</param>
		/// <exception cref="T:System.ArgumentOutOfRangeException">arrayIndex is less than 0.</exception>
		/// <exception cref="T:System.ArgumentNullException">array is null.</exception>
		/// <exception cref="T:System.ArgumentException">array is multidimensional.-or-arrayIndex is equal to or greater than the length of array.-or-The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"></see> is greater than the available space from arrayIndex to the end of the destination array.-or-Type T cannot be cast automatically to the type of the destination array.</exception>
		public void CopyTo( KeyValuePair<TKey, TValue>[] array, int arrayIndex )
		{
			throw new NotImplementedException();
		}

		/// <summary>
		/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"></see>.
		/// </summary>
		/// <value></value>
		/// <returns>The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"></see>.</returns>
		public int Count
		{
			get
			{
				lock( m_dictionary )
				{
					return m_dictionary.Count;
				}
			}
		}

		/// <summary>
		/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only.
		/// </summary>
		/// <value></value>
		/// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only; otherwise, false.</returns>
		public bool IsReadOnly
		{
			get
			{
				return false;
			}
		}

		/// <summary>
		/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"></see>.
		/// </summary>
		/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param>
		/// <returns>
		/// true if item was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"></see>; otherwise, false. This method also returns false if item is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"></see>.
		/// </returns>
		/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only.</exception>
		public bool Remove( KeyValuePair<TKey, TValue> item )
		{
			lock( m_dictionary )
			{
				ClearCachedLists();
				return m_dictionary.Remove( item.Key );
			}
		}

		/// <summary>
		/// Returns an enumerator that iterates through the collection.
		/// </summary>
		/// <returns>
		/// A <see cref="T:System.Collections.Generic.IEnumerator`1"></see> that can be used to iterate through the collection.
		/// </returns>
		public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
		{
			throw new NotImplementedException();
		}

		/// <summary>
		/// Returns an enumerator that iterates through a collection.
		/// </summary>
		/// <returns>
		/// An <see cref="T:System.Collections.IEnumerator"></see> object that can be used to iterate through the collection.
		/// </returns>
		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			throw new NotImplementedException();
		}

		/// <summary>
		/// Clears the cached lists.
		/// </summary>
		private void ClearCachedLists()
		{
			m_cachedKeyList = null;
			m_cachedValueList = null;
		}

		/// <summary>
		/// Holds the internal data values and the time that they expire
		/// </summary>
		/// <typeparam name="TNodeValue"></typeparam>
		private class DataNode<TNodeValue>
		{
			// Local Instance Values
			private DateTime m_expirers;
			private TNodeValue m_value;

			// Local Static Values
			private static int s_ttl= 300;

			/// <summary>
			/// Initializes a new instance of the <see cref="T:DataNode&lt;TValue&gt;"/> class.
			/// </summary>
			/// <param name="value">The value.</param>
			public DataNode( TNodeValue value )
			{
				m_expirers = DateTime.Now.AddSeconds( s_ttl );
				m_value = value;
			}

			/// <summary>
			/// Gets the expirers.
			/// </summary>
			/// <value>The expirers.</value>
			public DateTime Expirers
			{
				get
				{
					return m_expirers;
				}
			}

			/// <summary>
			/// Gets a value indicating whether this instance is expired.
			/// </summary>
			/// <value>
			/// 	<c>true</c> if this instance is expired; otherwise, <c>false</c>.
			/// </value>
			public bool IsExpired
			{
				get
				{
					return ( m_expirers < DateTime.Now );
				}
			}

			/// <summary>
			/// Gets the value.
			/// </summary>
			/// <value>The value.</value>
			public TNodeValue Value
			{
				get
				{
					return m_value;
				}

				set
				{
					m_value = value;
				}
			}

			/// <summary>
			/// Gets or sets the TTL in seconds for the objects to expire.
			/// </summary>
			/// <value>The TTL.</value>
			public static int TTL
			{
				get
				{
					return s_ttl;
				}

				set
				{
					s_ttl = value;
				}
			}
		}
	}
}
